package com.heima.admin.logAspect;

import com.heima.admin.annotation.webLog;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.mapper.AdUserOperationlogMapper;
import com.heima.common.exception.CustException;
import com.heima.model.admin.pojo.AdUser;
import com.heima.model.admin.pojo.AdUserOperationlog;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AdminThreadLocalUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@Aspect //开启切面
public class webLogAspect {
    @Autowired
    AdUserMapper adUserMapper;
    @Autowired
    AdUserOperationlogMapper adUserOperationlogMapper;

    @Pointcut("@annotation(com.heima.admin.annotation.webLog)")
    public void pt() {
    }

    @Around("pt()")
    public Object around(ProceedingJoinPoint pjp) {
        Object result = null;
        try {
            long start = System.currentTimeMillis();
            result = pjp.proceed();
            long end = System.currentTimeMillis();
            ServletRequestAttributes request = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (request == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //全限名
            Signature signature = pjp.getSignature();
            String className = signature.getDeclaringTypeName() + "." + signature.getName();
            //请求方式
            String method = request.getRequest().getMethod();
            //请求的url
            String contextPath = request.getRequest().getRequestURI();
            //操作
            webLog annotation = ((MethodSignature) pjp.getSignature()).getMethod().getAnnotation(webLog.class);
            String requestOperation = annotation.value();
            //获取登录对象
            AdUser user = AdminThreadLocalUtils.getUser();
            if (user == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //操作人id
            Integer id = user.getId();
            AdUser adUser = adUserMapper.selectById(id);
            if (adUser == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //操作人name
            String name = adUser.getName();
            //操作时间
            long time = end - start;
            String ipAddr = getIpAddr(request.getRequest());
            AdUserOperationlog adUserOperationlog = new AdUserOperationlog();
            adUserOperationlog.setMethodName(className);
            adUserOperationlog.setRequestMethod(method);
            adUserOperationlog.setRequestPath(contextPath);
            adUserOperationlog.setRequestOperation(requestOperation);
            adUserOperationlog.setOperator(name);
            adUserOperationlog.setOperatorId(adUser.getId());
            adUserOperationlog.setExecuteTime((int) time);
            adUserOperationlog.setRemoteAddr(ipAddr);
            adUserOperationlog.setCreateTime(new Date());
            adUserOperationlogMapper.insert(adUserOperationlog);

        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return result;
    }


    /**
     * 获取真实IP地址
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String unknown = "unknown";
        String ip0 = request.getHeader("x-forwarded-for");
        String ip = request.getHeader("X-Real-IP");

        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.equals("0:0:0:0:0:0:0:1")) {
            ip = "local";
        }
        return ip;
    }
}
